### Bootstrap the baseline model specification

date()
library("tidyverse")
library("foreach")
library("maxLik")
source("backend_main.r")
sessionInfo()


load("confirm_boot_base.rda")
load("startvals_fit_base.rda")
load("results/fit_base.rda")
load("results/boot_index_base.rda")


## Set to FALSE to estimate from scratch (takes much longer)
CONFIRM_MODE <- TRUE

## Run bootstrap using indices generated in previous script
boot_base <- vector("list", length(fit_base))
for (i in seq_along(boot_base)) {
  fit <- fit_base[[i]]
  boot_base[[i]] <- foreach (b = 1:100, .combine = "rbind") %do% {
    cat("Imputation ", i, ", bootstrap iteration ", b, ", ", date(), "\n", sep = "")
    id_disp_boot <- boot_index_base[[i]][b, ]
    id_map <- tibble(id = seq_along(id_disp_boot), id_old = id_disp_boot)
    boot_dispute <-  left_join(id_map,
                               fit$data_dispute,
                               by = c("id_old" = "id"))
    boot_participant <- left_join(id_map,
                                  fit$data_participant,
                                  by = c("id_old" = "id"))
    if (CONFIRM_MODE) {
      init <- confirm_boot_base[[i]][b, ]
    } else {
      init <- startvals_fit_base[[i]]
    }
    boot_cf <- est_structwar_ac(f_dispute = fit$f_dispute,
                                f_participant = fit$f_participant,
                                data_dispute = boot_dispute,
                                data_participant = boot_participant,
                                n_halton = fit$n_halton,
                                coef_only = TRUE,
                                init = init,
                                init_fallback = startvals_fit_base[[i]],
                                scale = FALSE,
                                reltol = 1e-14,
                                iterlim = 5000,
                                useGrad = TRUE,
                                finalHessian = FALSE,
                                printLevel = 1)
    boot_cf
  }
}


save(boot_base, file = "results/boot_base.rda")


date()
